<template>
  <div class="pin_page">
      <input ref="pin" type="text" maxlength="6" v-model="pin" @blur="blur"/>
      <ul class="pwd-wrap" @click="focus">
        <li v-for="(item, index) in 6" :class="{selected: selectedLine == index}"  v-show="show">
          <i :class="{inputed: pinLength > index}"></i>
        </li>
        <li v-for="(item, index) in 6" :key="item" :class="{selected: selectedLine == index}" v-show="!show">{{arr[index]}}</li>
      </ul>
  </div>

</template>

<script>
export default {
  props: ['isFocus', 'show'],
  data () {
    return {
      pin: '',
      pinLength: -1,
      arr: [],
      selectedLine: -1
    }
  },
  methods: {
    getNum () {
      this.arr = this.pin.split('')
    },
    focus () {
      this.$refs.pin.focus()
      // 选中时下划线跟着输入的数量显示
      this.selectedLine = this.pin.length || 0
    },
    // 失焦去除选择下划线
    blur () {
      this.selectedLine = -1
    }
  },
  mounted () {
    if (this.isFocus) {
      this.focus()
    }
  },
  watch: {
    pin (value) {
      if (/[^\d]/g.test(value)) {
        this.pin = this.pin.replace(/[^\d]/g, '')
      } else {
        this.pinLength = value.length
        // 选中下划线跟着输入的数量显示
        this.selectedLine = value.length
      }
      this.$emit('PIN', value.trim())
      this.getNum()
    }
  }
}
</script>

<style lang="less">
    .pin_page {
      width: 100%;

      input {
        position: absolute;
        z-index: -1;
        opacity: 0
      }
      .pwd-wrap {
        width: 300px;
        margin: 0 auto;
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        li {
          width: 14%;
          height: 40px;
          border-bottom: solid 1px #4E5A84;
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;
          cursor:text;
          color: #fff;

          &:last-child{ margin-right:0;}

          i {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
          }

          .inputed {
            background-color: #C0C5D0;
          }
        }
        .selected {
          border-bottom: solid 1px #516ED0;
        }
      }

    }
</style>
